import 'package:chathouse/model/push_model.dart';
import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/pages/expert/service_detail.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/public/empty_widget.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../constant/app_constant.dart';
import '../../model/member_info.dart';
import '../../widgets/base_appbar.dart';
import '../base/base.dart';
import 'confirm_service.dart';

class NoticePage extends BaseStatefulWidget {
  @override
  _NoticePageState createState() => _NoticePageState();
}

class _NoticePageState extends BaseStatefulWidgetState<NoticePage>
    with AutomaticKeepAliveClientMixin {
  PushModel? model;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false); // 刷新控件控制

  int pageNum = 1;
  List<Rows>? rows = [];

  @override
  void initState() {
    super.initState();
    updateEmptyPage(tipTitle: "無通知信息");
    updateState(LoadState.success);
    setState(() {
      scaffoldBackColor = Colors.white;
    });
    load();
  }

  loadMore() {
    pageNum += 1;
    load();
  }

  clearLoad() {
    pageNum = 1;
    rows?.clear();
    load();
  }

  load() {
    Obj.showLoading();
    Object? json = SpUtil.getObject2(AppConstant.memberInfo);
    if (json != null) {
      MemberInfo memberInfo = MemberInfo.fromJson2(json);
      final params = {
        "membersId": memberInfo.data?.membersId,
        "kind": "1",
        "pageNum": pageNum
      };
      Apis.getPushList(params).then((response) {
        Obj.dismissLoading();
        _refreshController.refreshCompleted();
        _refreshController.loadComplete();
        var data = response?.data;
        model = PushModel.fromJson(data);
        rows?.addAll(model?.rows ?? []);
        setState(() {});
      }).onError((error, stackTrace) {
        _refreshController.refreshCompleted();
        _refreshController.loadComplete();
        Obj.dismissLoading();
      });
    }
  }

  messageRead(Rows item) {
    Obj.showLoading();
    Apis.messageReadSet({"longList": item.informId.toString()})
        .then((response) {
      Obj.dismissLoading();
      _refreshController.refreshCompleted();
      setState(() {});
    }).onError((error, stackTrace) {
      _refreshController.refreshCompleted();
      Obj.dismissLoading();
    });
  }

  List<String> subStringByName(String name) {
    if (name.contains('"')) {
      int start = name.indexOf('"');
      int end = name.lastIndexOf('"');
      if (start >= 0 && end >= 0) {
        String part1 = name.substring(0, start);
        String part2 = name.substring(start + 1, end);
        String part3 = name.substring(end + 1);
        return [part1, part2, part3];
      }
    }
    return [name];
  }

  Widget messageItem(Rows item) {
    String name = item.informComment ?? "";
    return InkWell(
      onTap: () {
        messageRead(item);
        item.readFlag = "1";
        Get.to(ExpertServiceDetailPage(item!.projectId!));
        setState(() {});
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        color: Colors.white,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Column(
                    children: [
                      Container(
                        child: Text(
                          "${item.informComment}",
                          maxLines: 3,
                          style: getTextStyle(24.sp,
                              fontType: FontType.MID, color: Styles.c_191919),
                        ),
                      ),
                      SizedBox(
                        height: 12.w,
                      ),
                      Visibility(
                        visible: (item?.serviceName ?? "").isNotEmpty,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          child: Container(
                              // color: Styles.mainColor,
                              padding: EdgeInsets.symmetric(
                                  horizontal: 20.w, vertical: 6.w),
                              decoration: BoxDecoration(
                                color: Styles.mainColor,
                                borderRadius: BorderRadius.circular(20.w),
                              ),
                              child: Text(
                                item?.serviceName ?? "",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontSize: 16.w,
                                    fontWeight: FontWeight.w500,
                                    color: Colors.white),
                              )),
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  width: 20.w,
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.w),
                  alignment: Alignment.topRight,
                  child: Text(
                    "${item.createTime}",
                    maxLines: 3,
                    style: getTextStyle(14.sp,
                        fontType: FontType.MID, color: Styles.c_666),
                  ),
                ),
              ],
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 12),
              width: double.infinity,
              child: item.readFlag == "0"
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text("新消息",
                            style: getTextStyle(14.sp,
                                fontType: FontType.BOLD,
                                color: Colors.redAccent)),
                        const SizedBox(
                          width: 4,
                        ),
                        Container(
                          width: 6,
                          height: 6,
                          decoration: BoxDecoration(
                              color: Colors.redAccent,
                              borderRadius: BorderRadius.circular(3)),
                        )
                      ],
                    )
                  : Container(),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: getAppBar(leading: Container(), title: "通知"),
      body: rows?.length == 0
          ? const Align(
              child: EmptyWidget(
                emptyText: '暂無通知數據',
              ),
              alignment: Alignment.center,
            )
          : SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              controller: _refreshController,
              onRefresh: clearLoad,
              onLoading: () {
                loadMore();
              },
              child: ListView.separated(
                  shrinkWrap: true,
                  itemCount: rows?.length ?? 0,
                  itemBuilder: (context, index) {
                    return messageItem(rows![index]);
                  },
                  separatorBuilder: (context, index) {
                    return Container(
                      height: 0.6,
                      color: Styles.c_ccc,
                    );
                  }),
            ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
